LoginSignup
35
30

More than 5 years have passed since last update.

golangでWebアプリケーションのルーティングを実装する!

Last updated at Posted at 2019-03-15

はじめに

golangでWebアプリケーションのルーティングを実装する方法を覚えたのでアウトプットします!

実装ページ

スクリーンショット 2019-03-15 20.24.19.png


スクリーンショット 2019-03-15 20.18.41.png


スクリーンショット 2019-03-15 20.19.17.png


コード

package main

import (
    "fmt"
    "net/http"
)

//「http://localhost:8080/hello」の処理
func helloHandle(w http.ResponseWriter, r *http.Request) {
    h := `
        <html>
            <head>
                <title>Hello</title>
            </head>
            <body>
                Hello
            </body>
        </html>
        `
    fmt.Fprint(w, h)
}

//「http://localhost:8080/goodbye」の処理
func goodbyeHandle(w http.ResponseWriter, r *http.Request) {
    h := `
        <html>
            <head>
                <title>goodbye</title>
            </head>
            <body>
                goodbye
            </body>
        </html>
        `
    fmt.Fprint(w, h)
}

//「http://localhost:8080/」の処理
func landingHandle(w http.ResponseWriter, r *http.Request) {
    h := `
        <html>
            <head>
                <title>Landing</title>
            </head>
            <body>
                Landing
            </body>
        </html>
        `
    fmt.Fprint(w, h)
}

func main() {
    // URLごとに関数を登録
    http.HandleFunc("/hello", helloHandle)
    http.HandleFunc("/goodbye", goodbyeHandle)
    http.HandleFunc("/", landingHandle)

    //Webサーバを起動
    if err := http.ListenAndServe(":8080", nil); err != nil {
        fmt.Println(err)
    }
}
35
30
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
35
30