Skip to content

DevNewbie1826/httperror

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

httperror

Go Report Card GoDoc codecov

A simple, lightweight Go package for centralized HTTP error handling, using helper functions to generate standard HTTP error responses directly.


English

πŸ“– Overview

httperror provides a simple way to handle errors in your Go web application without complex middleware configurations. It offers a set of helper functions that directly write standardized JSON (or HTML) error responses to the http.ResponseWriter. It also supports a global error handler configuration for custom error rendering.

πŸš€ Installation

go get github.com/DevNewbie1826/httperror

✨ Features

  • Direct Usage: No middleware required. Call httperror.NotFound(w, r) directly in your handlers.
  • Standardized Responses: Default error handler responds with JSON (or HTML for browsers) automatically.
  • Customizable: You can replace the default error handler globally using httperror.SetErrorHandler.
  • Comprehensive Helpers: Covers almost all standard HTTP error status codes (e.g., httperror.BadRequest, httperror.Forbidden, etc.).

πŸ’‘ Usage

Basic Example

Simply import the package and use the helper functions in your HTTP handlers.

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/DevNewbie1826/httperror"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello, World!")
	})

	http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
		// Some logic to find a user...
		userFound := false

		if !userFound {
			// Directly respond with a 404 Not Found error.
			// This writes the status code and the JSON body to the ResponseWriter.
			httperror.NotFound(w, r, "User with the specified ID was not found.")
			return
		}

		fmt.Fprintln(w, "User data would be here.")
	})
    
    http.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
        // Respond with a 403 Forbidden error using the default message.
        httperror.Forbidden(w, r)
    })

	log.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

When you run this server and access http://localhost:8080/users, you will get a JSON response like this:

{
	"status": 404,
	"message": "User with the specified ID was not found."
}

Custom Error Handler

You can provide your own custom error handling logic globally using SetErrorHandler. This is useful if you want to render custom HTML error pages or change the JSON structure.

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/DevNewbie1826/httperror"
)

func main() {
	// Set a custom global error handler.
	httperror.SetErrorHandler(func(w http.ResponseWriter, r *http.Request, err error) {
		// You can type-assert to access the status code if needed
		status := http.StatusInternalServerError
		message := "Internal Server Error"
		
		if httpErr, ok := err.(*httperror.HttpError); ok {
			status = httpErr.Status
			message = httpErr.Message
		}
		
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		fmt.Fprintf(w, `{"error": true, "code": %d, "msg": "%s"}`, status, message)
	})

	http.HandleFunc("/oops", func(w http.ResponseWriter, r *http.Request) {
		httperror.BadRequest(w, r, "Something went wrong!")
	})

	log.Println("Server starting on :8080")
	http.ListenAndServe(":8080", nil)
}

ν•œκ΅­μ–΄

πŸ“– κ°œμš”

httperrorλŠ” λ³΅μž‘ν•œ 미듀웨어 μ„€μ • 없이 Go μ›Ή μ• ν”Œλ¦¬μΌ€μ΄μ…˜μ˜ 였λ₯˜λ₯Ό μ²˜λ¦¬ν•  수 μžˆλŠ” κ°„λ‹¨ν•˜κ³  κ°€λ²Όμš΄ νŒ¨ν‚€μ§€μž…λ‹ˆλ‹€. http.ResponseWriter에 ν‘œμ€€ν™”λœ JSON(λ˜λŠ” λΈŒλΌμš°μ €μ˜ 경우 HTML) 였λ₯˜ 응닡을 직접 μž‘μ„±ν•˜λŠ” 헬퍼 ν•¨μˆ˜λ“€μ„ μ œκ³΅ν•©λ‹ˆλ‹€. λ˜ν•œ, μ „μ—­ 였λ₯˜ ν•Έλ“€λŸ¬ 섀정을 톡해 μ»€μŠ€ν…€ λ Œλ”λ§ λ‘œμ§μ„ μ μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

πŸš€ μ„€μΉ˜

go get github.com/DevNewbie1826/httperror

✨ μ£Όμš” κΈ°λŠ₯

  • 직관적인 μ‚¬μš©: 미듀웨어가 ν•„μš” μ—†μŠ΅λ‹ˆλ‹€. ν•Έλ“€λŸ¬μ—μ„œ httperror.NotFound(w, r)와 같이 직접 ν˜ΈμΆœν•˜μ„Έμš”.
  • ν‘œμ€€ν™”λœ 응닡: κΈ°λ³Έ 였λ₯˜ ν•Έλ“€λŸ¬κ°€ μžλ™μœΌλ‘œ JSON(λ˜λŠ” λΈŒλΌμš°μ € μš”μ²­ μ‹œ HTML)으둜 μ‘λ‹΅ν•©λ‹ˆλ‹€.
  • μ»€μŠ€ν„°λ§ˆμ΄μ§•: httperror.SetErrorHandlerλ₯Ό μ‚¬μš©ν•˜μ—¬ κΈ°λ³Έ 였λ₯˜ ν•Έλ“€λŸ¬λ₯Ό μ „μ—­μ μœΌλ‘œ ꡐ체할 수 μžˆμŠ΅λ‹ˆλ‹€.
  • 포괄적인 헬퍼: 거의 λͺ¨λ“  ν‘œμ€€ HTTP 였λ₯˜ μƒνƒœ μ½”λ“œλ₯Ό μ§€μ›ν•©λ‹ˆλ‹€ (예: httperror.BadRequest, httperror.Forbidden λ“±).

πŸ’‘ μ‚¬μš©λ²•

기본 예제

νŒ¨ν‚€μ§€λ₯Ό import ν•˜κ³  HTTP ν•Έλ“€λŸ¬ λ‚΄μ—μ„œ 헬퍼 ν•¨μˆ˜λ₯Ό 직접 μ‚¬μš©ν•˜μ‹œλ©΄ λ©λ‹ˆλ‹€.

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/DevNewbie1826/httperror"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello, World!")
	})

	http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
		// μ‚¬μš©μžλ₯Ό μ°ΎλŠ” 둜직이 μžˆλ‹€κ³  κ°€μ •...
		userFound := false

		if !userFound {
			// 404 Not Found 였λ₯˜λ‘œ μ¦‰μ‹œ μ‘λ‹΅ν•©λ‹ˆλ‹€.
			// 이 ν•¨μˆ˜κ°€ μƒνƒœ μ½”λ“œμ™€ JSON 본문을 ResponseWriter에 μž‘μ„±ν•©λ‹ˆλ‹€.
			httperror.NotFound(w, r, "μ§€μ •λœ ID의 μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.")
			return
		}

		fmt.Fprintln(w, "μ‚¬μš©μž 데이터가 여기에 좜λ ₯λ©λ‹ˆλ‹€.")
	})
    
    http.HandleFunc("/admin", func(w http.ResponseWriter, r *http.Request) {
        // κΈ°λ³Έ λ©”μ‹œμ§€λ₯Ό μ‚¬μš©ν•˜μ—¬ 403 Forbidden 였λ₯˜λ₯Ό μ‘λ‹΅ν•©λ‹ˆλ‹€.
        httperror.Forbidden(w, r)
    })

	log.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

이 μ„œλ²„λ₯Ό μ‹€ν–‰ν•˜κ³  http://localhost:8080/users μ£Όμ†Œλ‘œ μ ‘μ†ν•˜λ©΄, λ‹€μŒκ³Ό 같은 JSON 응닡을 λ°›κ²Œ λ©λ‹ˆλ‹€.

{
	"status": 404,
	"message": "μ§€μ •λœ ID의 μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
}

μ‚¬μš©μž μ •μ˜ 였λ₯˜ ν•Έλ“€λŸ¬

SetErrorHandlerλ₯Ό μ‚¬μš©ν•˜λ©΄ μ „μ—­ 였λ₯˜ 처리 λ‘œμ§μ„ 직접 μ •μ˜ν•  수 μžˆμŠ΅λ‹ˆλ‹€. μ»€μŠ€ν…€ HTML 였λ₯˜ νŽ˜μ΄μ§€λ₯Ό λ Œλ”λ§ν•˜κ±°λ‚˜ JSON ꡬ쑰λ₯Ό λ³€κ²½ν•˜κ³  싢을 λ•Œ μœ μš©ν•©λ‹ˆλ‹€.

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/DevNewbie1826/httperror"
)

func main() {
	// μ»€μŠ€ν…€ μ „μ—­ 였λ₯˜ ν•Έλ“€λŸ¬ μ„€μ •
	httperror.SetErrorHandler(func(w http.ResponseWriter, r *http.Request, err error) {
		// ν•„μš”ν•˜λ‹€λ©΄ νƒ€μž… 단언(type assertion)을 톡해 μƒνƒœ μ½”λ“œμ— μ ‘κ·Όν•  수 μžˆμŠ΅λ‹ˆλ‹€.
		status := http.StatusInternalServerError
		message := "Internal Server Error"
		
		if httpErr, ok := err.(*httperror.HttpError); ok {
			status = httpErr.Status
			message = httpErr.Message
		}
		
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		fmt.Fprintf(w, `{"error": true, "code": %d, "msg": "%s"}`, status, message)
	})

	http.HandleFunc("/oops", func(w http.ResponseWriter, r *http.Request) {
		httperror.BadRequest(w, r, "무언가 잘λͺ»λ˜μ—ˆμŠ΅λ‹ˆλ‹€!")
	})

	log.Println("Server starting on :8080")
	http.ListenAndServe(":8080", nil)
}

πŸ“œ License

This project is licensed under the MIT License. See the LICENSE file for details.

About

A simple Go middleware for centralized HTTP error handling, with convenient helper functions for generating standard HTTP error responses.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages