package main
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"gopkg.in/mgo.v2"
)
func JsonMongo1(w http.ResponseWriter, r *http.Request) {
info := &mgo.DialInfo{
Addrs: []string{"localhost:27017"},
Database: "name_store",
Username: "shiro",
Password: "123",
Source: "admin",
}
//通常
//session, err := mgo.Dial("localhost:27017")
//認証
session, err := mgo.DialWithInfo(info)
if err != nil {
return
}
defer session.Close()
c := session.DB("name_store").C("names")
t := []T{}
//1件取得
//if err := c.Find(bson.M{"name": "taro"}).One(&t); != nil{
// log.Print(err)
//}
if err := c.Find(nil).All(&t); err != nil {
log.Print(err)
}
w.Header().Set("content-type", "application/json;charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(t); err != nil {
return
}
}
func TemplateHtml(w http.ResponseWriter, r *http.Request) {
p, err := os.Executable()
if err != nil {
return
}
t := template.Must(template.ParseFiles(filepath.FromSlash(filepath.Dir(p) + "/index.html")))
if err := t.Execute(w, nil); err != nil {
return
}
}
func TemplateText(w http.ResponseWriter, r *http.Request) {
p, err := os.Executable()
if err != nil {
return
}
f, err := ioutil.ReadFile(filepath.FromSlash(filepath.Dir(p) + "/vue.html"))
if err != nil {
return
}
fmt.Fprint(w, string(f))
}
func FromPost(w http.ResponseWriter, r *http.Request) {
info := &mgo.DialInfo{
Addrs: []string{"localhost:27017"},
Database: "name_store",
Username: "shiro",
Password: "123",
Source: "admin",
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Print(err)
}
t := []T{}
if err := json.Unmarshal(body, &t); err != nil {
log.Print(err)
}
//認証
session, err := mgo.DialWithInfo(info)
if err != nil {
log.Print(err)
}
defer session.Close()
c := session.DB("name_store").C("names")
err = c.Insert(&t[0])
if err != nil {
log.Print(err)
}
}
func main() {
http.HandleFunc("/1", RequestParams)
http.HandleFunc("/2", QueryKeyValue)
http.HandleFunc("/3", ResponseJson)
http.HandleFunc("/4", JsonMongo1)
http.HandleFunc("/5", TemplateHtml)
http.HandleFunc("/6", TemplateText)
http.HandleFunc("/7", FromPost)
if err := http.ListenAndServe(":9000", nil); err != nil {
log.Fatal(err)
}
}
func RequestParams(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
return
}
fmt.Fprintf(w, "%s\n", r.URL.Host)
fmt.Fprintf(w, "%s\n", r.URL.Path)
fmt.Fprintf(w, "%s\n", r.URL.RawQuery)
}
func QueryKeyValue(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
return
}
for key, value := range r.URL.Query() {
fmt.Fprintf(w, "key: %s\n", key)
for i, v := range value {
fmt.Fprintf(w, "value[%d]: %s\n", i, v)
}
}
}
type T struct {
ID json.Number
Name string
}
func ResponseJson(w http.ResponseWriter, r *http.Request) {
t := T{
ID: "1",
Name: "taro",
}
w.Header().Set("content-type", "application/json;charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(t); err != nil {
return
}
}