gryffyn 4 months ago
commit
b8b34988c9
Signed by: gryffyn GPG Key ID: 6948DD6514D02BEF
  1. 3
      .gitignore
  2. 8
      go.mod
  3. 111
      main.go

3
.gitignore

@ -0,0 +1,3 @@
helpfulweatheradvisor
.idea/
go.sum

8
go.mod

@ -0,0 +1,8 @@
module git.neveris.one/gryffyn/helpfulweatheradvisor
go 1.15
require (
github.com/gorilla/mux v1.8.0
github.com/urfave/cli/v2 v2.3.0
)

111
main.go

@ -0,0 +1,111 @@
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/urfave/cli/v2"
)
func Run() {
var location string
var port int
app := &cli.App{
Name: "exren",
Version: "v0.1.3",
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Aliases: []string{"p"},
Usage: "Port to bind to, by default 8585",
Destination: &port,
Required: false,
},
&cli.StringFlag{
Name: "location",
Aliases: []string{"l"},
Usage: "subdirectory to run in (including forward slash - for example '/weather')",
Destination: &location,
Required: false,
},
},
Action: func(c *cli.Context) error {
err := serve(c.String("location"), c.Int("port"))
return err
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
type Data struct {
Country string `json:"country"`
PostCode string `json:"postcode"`
SuggestedClothing string `json:"suggested_clothing"`
}
func getReturn(w http.ResponseWriter, r *http.Request) {
countries, okc := r.URL.Query()["country"]
postcodes, okp := r.URL.Query()["postcode"]
if (!okc && !okp) || len(countries[0]) < 1 && len(postcodes[0]) < 1 {
w.Write([]byte("params 'country' and 'postcode' are missing"))
return
}
if !okc || len(countries[0]) < 1 {
w.Write([]byte("param 'country' is missing"))
return
}
if !okp || len(postcodes[0]) < 1 {
w.Write([]byte("param 'postcode' is missing"))
return
}
data := Data{
Country: countries[0],
PostCode: postcodes[0],
SuggestedClothing: "clothes",
}
jData, err := json.Marshal(data)
if err != nil {
log.Println("error marshalling data")
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
}
func makeMuxRouter(loc string) http.Handler {
r := mux.NewRouter().StrictSlash(true)
if loc == "" { loc = "/" }
r.HandleFunc(loc, getReturn).Methods("GET")
return r
}
func serve(loc string, port int) error {
handlr := makeMuxRouter(loc)
if port == 0 { port = 8585 }
s := &http.Server{
Addr: "127.0.0.1:" + strconv.Itoa(port),
Handler: handlr,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
log.Println("Serving on 127.0.0.1:" + strconv.Itoa(port))
err := s.ListenAndServe()
return err
}
func main() {
Run()
}
Loading…
Cancel
Save