Go Web编程 Chapter4

Go web编程

Chapter_4 Processing_Requests

body
package main

import (
	"fmt"
	"net/http"
)

func body(w http.ResponseWriter, r *http.Request) {
	len := r.ContentLength
	body := make([]byte, len)
	r.Body.Read(body)
	fmt.Fprintln(w, string(body))
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/body", body)
	server.ListenAndServe()
}
package main

import (
   "fmt"
   "net/http"
)

func setCookie(w http.ResponseWriter, r *http.Request) {
   c1 := http.Cookie{
      Name:     "first_cookie",
      Value:    "Go Web Programming",
      HttpOnly: true,
   }
   c2 := http.Cookie{
      Name:     "second_cookie",
      Value:    "Manning Publications Co",
      HttpOnly: true,
   }
   http.SetCookie(w, &c1)
   http.SetCookie(w, &c2)
}

func getCookie(w http.ResponseWriter, r *http.Request) {
   c1, err := r.Cookie("first_cookie")
   if err != nil {
      fmt.Fprintln(w, "Cannot get the first cookie")
   }
   cs := r.Cookies()
   fmt.Fprintln(w, c1)
   fmt.Fprintln(w, cs)
}

func main() {
   server := http.Server{
      Addr: "127.0.0.1:8080",
   }
   http.HandleFunc("/set_cookie", setCookie)
   http.HandleFunc("/get_cookie", getCookie)
   server.ListenAndServe()
}
package main

import (
   "encoding/base64"
   "fmt"
   "net/http"
   "time"
)

func setMessage(w http.ResponseWriter, r *http.Request) {
   msg := []byte("Hello World!")
   c := http.Cookie{
      Name:  "flash",
      Value: base64.URLEncoding.EncodeToString(msg),
   }
   http.SetCookie(w, &c)
}

func showMessage(w http.ResponseWriter, r *http.Request) {
   c, err := r.Cookie("flash")
   if err != nil {
      if err == http.ErrNoCookie {
         fmt.Fprintln(w, "No message found")
      }
   } else {
      rc := http.Cookie{
         Name:    "flash",
         MaxAge:  -1,
         Expires: time.Unix(1, 0),
      }
      http.SetCookie(w, &rc)
      val, _ := base64.URLEncoding.DecodeString(c.Value)
      fmt.Fprintln(w, string(val))
   }
}

func main() {
   server := http.Server{
      Addr: "127.0.0.1:8080",
   }
   http.HandleFunc("/set_message", setMessage)
   http.HandleFunc("/show_message", showMessage)
   server.ListenAndServe()
}
fileupload
package main

import (
   "fmt"
   "io/ioutil"
   "net/http"
)

func process(w http.ResponseWriter, r *http.Request) {
   r.ParseMultipartForm(1024)
   fileHeader := r.MultipartForm.File["uploaded"][0]
   file, err := fileHeader.Open()
   if err == nil {
      data, err := ioutil.ReadAll(file)
      if err == nil {
         fmt.Fprintln(w, string(data))
      }
   }
}

func main() {
   server := http.Server{
      Addr: "127.0.0.1:8080",
   }
   http.HandleFunc("/process", process)
   server.ListenAndServe()
}

client.html网页

<html>
  <head>    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Go Web Programming</title>
  </head>
  <body>
    <form action="http://localhost:8080/process?hello=world&thread=123" method="post" enctype="multipart/form-data">
      <input type="text" name="hello" value="sau sheong"/>
      <input type="text" name="post" value="456"/>
      <input type="file" name="uploaded">
      <input type="submit">
    </form>
  </body>
</html>
form
package main

import (
   "fmt"
   "net/http"
)

func process(w http.ResponseWriter, r *http.Request) {
   r.ParseForm()
   fmt.Fprintln(w, r.Form)
}

func main() {
   server := http.Server{
      Addr: "127.0.0.1:8080",
   }
   http.HandleFunc("/process", process)
   server.ListenAndServe()
}

client.html网页

<html>
  <head>    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Go Web Programming</title>
  </head>
  <body>
    <form action="http://127.0.0.1:8080/process?hello=world&thread=123" method="post" enctype="application/x-www-form-urlencoded">
      <input type="text" name="hello" value="sau sheong"/>
      <input type="text" name="post" value="456"/>
      <input type="submit"/>
    </form>
  </body>
</html>
formfile
package main

import (
   "fmt"
   "io/ioutil"
   "net/http"
)

func process(w http.ResponseWriter, r *http.Request) {
   file, _, err := r.FormFile("uploaded")
   if err == nil {
      data, err := ioutil.ReadAll(file)
      if err == nil {
         fmt.Fprintln(w, string(data))
      }
   }
}

func main() {
   server := http.Server{
      Addr: "127.0.0.1:8080",
   }
   http.HandleFunc("/process", process)
   server.ListenAndServe()
}

client.html网页

<html>
  <head>    
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Go Web Programming</title>
  </head>
  <body>
    <form action="http://localhost:8080/process?hello=world&thread=123" method="post" enctype="multipart/form-data">
      <input type="text" name="hello" value="sau sheong"/>
      <input type="text" name="post" value="456"/>
      <input type="file" name="uploaded">
      <input type="submit">
    </form>
  </body>
</html>
package main

import (
   "fmt"
   "net/http"
)

func headers(w http.ResponseWriter, r *http.Request) {
   h := r.Header
   fmt.Fprintln(w, h)
}

func main() {
   server := http.Server{
      Addr: "127.0.0.1:8080",
   }
   http.HandleFunc("/headers", headers)
   server.ListenAndServe()
}
write
package main

import (
   "encoding/json"
   "fmt"
   "net/http"
)

type Post struct {
   User    string
   Threads []string
}

func writeExample(w http.ResponseWriter, r *http.Request) {
   str := `<html>
<head><title>Go Web Programming</title></head>
<body><h1>Hello World</h1></body>
</html>`
   w.Write([]byte(str))
}

func writeHeaderExample(w http.ResponseWriter, r *http.Request) {
   w.WriteHeader(501)
   fmt.Fprintln(w, "No such service, try next door")
}

func headerExample(w http.ResponseWriter, r *http.Request) {
   w.Header().Set("Location", "http://google.com")
   w.WriteHeader(302)
}

func jsonExample(w http.ResponseWriter, r *http.Request) {
   w.Header().Set("Content-Type", "application/json")
   post := &Post{
      User:    "Sau Sheong",
      Threads: []string{"first", "second", "third"},
   }
   json, _ := json.Marshal(post)
   w.Write(json)
}

func main() {
   server := http.Server{
      Addr: "127.0.0.1:8080",
   }
   http.HandleFunc("/write", writeExample)
   http.HandleFunc("/writeheader", writeHeaderExample)
   http.HandleFunc("/redirect", headerExample)
   http.HandleFunc("/json", jsonExample)
   server.ListenAndServe()
}
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy