Created
August 12, 2014 12:02
-
-
Save niratama/b6f71d45e7cb2c09b1d1 to your computer and use it in GitHub Desktop.
hikarie.go #2最後のお題
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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