Skip to content

Instantly share code, notes, and snippets.

@niratama
Created August 12, 2014 12:02
Show Gist options
  • Save niratama/b6f71d45e7cb2c09b1d1 to your computer and use it in GitHub Desktop.
Save niratama/b6f71d45e7cb2c09b1d1 to your computer and use it in GitHub Desktop.
hikarie.go #2最後のお題
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func (u User) ToJSON() string {
b, err := json.Marshal(u)
if err != nil {
fmt.Errorf("%s", err)
}
return string(b)
}
func main() {
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
queryParam := r.URL.Query()
var user User
user.Name = queryParam.Get("name")
user.Age, _ = strconv.Atoi(queryParam.Get("age"))
json := user.ToJSON()
fmt.Fprint(w, json)
ioutil.WriteFile("./apidata.txt", []byte(json), 0644)
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t, err := ioutil.ReadFile("./apidata.txt")
if err != nil {
fmt.Errorf("%s\n", err)
}
fmt.Fprint(w, string(t))
})
http.ListenAndServe(":4000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment