LoginSignup
0
1

More than 5 years have passed since last update.

Goサーバーへアクセスしたパスでの処理分岐

Last updated at Posted at 2013-07-03

アクセスしたパスでの処理振り分け方法に少し悩んだのでメモしておきます。
(package http の func pathMatch の定義を見て解決しました)

例ではhttp.Handleにはパターンとして"/app/"を登録し、ハンドラに渡されたパス("/app/post/(form|confirm|do)")をパターンマッチして処理を振り分けます。

server.go
package main

import (
    "fmt"
    "html"
    "net/http"
    "regexp"
)

type Router struct {
    config map[string]interface{}
}

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if m, _ := regexp.MatchString(`^/app/post/form$`, r.URL.Path); m {
        fmt.Fprintf(w, "Regist Form, %q", html.EscapeString(r.URL.Path))
    } else if m, _ := regexp.MatchString(`^/app/post/confirm$`, r.URL.Path); m {
        fmt.Fprintf(w, "Regist Confirm, %q", html.EscapeString(r.URL.Path))
    } else if m, _ := regexp.MatchString(`^/app/post/do$`, r.URL.Path); m {
        fmt.Fprintf(w, "Regist Do, %q", html.EscapeString(r.URL.Path))
    } else {
        fmt.Fprintf(w, "Other, %q", html.EscapeString(r.URL.Path))
    }
}

func main() {
    http.Handle("/app/", &Router{config: make(map[string]interface{})})
    http.Handle("/", http.FileServer(http.Dir("./static")))
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        panic(err)
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1