dongpouda6700 2019-04-09 07:23 采纳率: 100%
浏览 51
已采纳

models.go:声明为res,未使用

I can not reproduce this example although I have changed db name and password.Tree structure

.
├── main.go
├── main_test.go
├── models
│   └── models.go
└── utils
    └── encodeutils.go

Models

func InitDB() (*sql.DB, error) {
    var err error
    db, err := sql.Open("postgres", "postgres://miki:pass58@localhost/mydb?sslmode=disable")
    if err != nil {
        return nil, err
    } else {
        // Create model for our URL service
        stmt, err := db.Prepare("CREATE TABLE WEB_URL(ID SERIAL PRIMARY KEY, URL TEXT NOT NULL);")
        if err != nil {
            log.Println(err)
            return nil, err
        }
        res, err := stmt.Exec()
        if err != nil {
            log.Println(err)
            return nil, err
        }
        return db, nil
    }
}

main.go

import (
    "database/sql"
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"
    "time"

    "github.com/PacktPublishing/Building-RESTful-Web-Services-with-Go/Chapter07/urlshortener/models"
    base62 "github.com/PacktPublishing/Building-RESTful-Web-Services-with-Go/Chapter07/urlshortener/utils"
    "github.com/gorilla/mux"
    _ "github.com/lib/pq"
)

// DB stores the database session imformation. Needs to be initialized once
type DBClient struct {
    db *sql.DB
}

// Model the record struct
type Record struct {
    ID  int    `json:"id"`
    URL string `json:"url"`
}

// GetOriginalURL fetches the original URL for the given encoded(short) string
func (driver *DBClient) GetOriginalURL(w http.ResponseWriter, r *http.Request) {
    var url string
    vars := mux.Vars(r)
    // Get ID from base62 string
    id := base62.ToBase10(vars["encoded_string"])
    err := driver.db.QueryRow("SELECT url FROM web_url WHERE id = $1", id).Scan(&url)
    // Handle response details
    if err != nil {
        w.Write([]byte(err.Error()))
    } else {
        w.WriteHeader(http.StatusOK)
        w.Header().Set("Content-Type", "application/json")
        responseMap := map[string]interface{}{"url": url}
        response, _ := json.Marshal(responseMap)
        w.Write(response)
    }
}

// GenerateShortURL adds URL to DB and gives back shortened string
func (driver *DBClient) GenerateShortURL(w http.ResponseWriter, r *http.Request) {
    var id int
    var record Record
    postBody, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(postBody, &record)
    err := driver.db.QueryRow("INSERT INTO web_url(url) VALUES($1) RETURNING id", record.URL).Scan(&id)
    responseMap := map[string]interface{}{"encoded_string": base62.ToBase62(id)}
    if err != nil {
        w.Write([]byte(err.Error()))
    } else {
        w.Header().Set("Content-Type", "application/json")
        response, _ := json.Marshal(responseMap)
        w.Write(response)
    }
}

func main() {
    db, err := models.InitDB()
    if err != nil {
        panic(err)
    }
    dbclient := &DBClient{db: db}
    if err != nil {
        panic(err)
    }
    defer db.Close()
    // Create a new router
    r := mux.NewRouter()
    // Attach an elegant path with handler
    r.HandleFunc("/v1/short/{encoded_string:[a-zA-Z0-9]*}", dbclient.GetOriginalURL).Methods("GET")
    r.HandleFunc("/v1/short", dbclient.GenerateShortURL).Methods("POST")
    srv := &http.Server{
        Handler: r,
        Addr:    "127.0.0.1:8000",
        // Good practice: enforce timeouts for servers you create!
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }
    log.Fatal(srv.ListenAndServe())
}

When I run

go run /home/miki/go/src/github.com/PacktPublishing/Building-RESTful-Web-Services-with-Go/Chapter07/urlshortener/main.go

I got

go/src/github.com/PacktPublishing/Building-RESTful-Web-Services-with-Go/Chapter07/urlshortener/models/models.go:22:3: res declared and not used

Why? Models are initialized in main.

Just to show postqresql mydb=# \c mydb \dt

You are now connected to database "mydb" as user "postgres".
        List of relations
 Schema |  Name   | Type  | Owner 
--------+---------+-------+-------
 public | web_url | table | miki

If I try

_, err = stmt.Exec()
if err != nil {
    log.Println(err)
    return nil, err
}
return db, nil

Then

2019/04/09 09:35:58 pq: relation "web_url" already exists
panic: pq: relation "web_url" already exists
  • 写回答

1条回答 默认 最新

  • dtnat80842 2019-04-09 07:27
    关注

    the error message is clear, res, defined in model, see below, declared and not used

    res, err := stmt.Exec()
    if err != nil {
      log.Println(err)
      return nil, err
    }
    return db, nil
    

    if you don't care about res, can use _ to ignore it

    _, err = stmt.Exec()
    if err != nil {
      log.Println(err)
      return nil, err
    }
    return db, nil
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里