Golang bytes.HasSuffix Function

The bytes.HasSuffix function in Golang is part of the bytes package and is used to determine whether a byte slice ends with a specified suffix. It returns true if the byte slice ends with the given suffix and false otherwise. This function is particularly useful when you need to check for specific endings in data, such as file extensions, URL paths, or protocol terminators.

Table of Contents

  1. Introduction
  2. bytes.HasSuffix Function Syntax
  3. Examples
    • Basic Usage
    • Suffix Not Found
    • Checking for Multiple Suffixes
  4. Real-World Use Case
  5. Conclusion

Introduction

The bytes.HasSuffix function is useful for quickly checking whether a byte slice ends with a specific sequence of bytes. This is commonly used in scenarios like verifying file extensions, parsing URLs, or handling data with known suffixes.

bytes.HasSuffix Function Syntax

The syntax for the bytes.HasSuffix function is as follows:

func HasSuffix(s, suffix []byte) bool

Parameters:

  • s: The byte slice to be checked.
  • suffix: The suffix byte slice to compare against the end of s.

Returns:

  • bool: true if the byte slice s ends with the suffix suffix, and false otherwise.

Examples

Basic Usage

This example demonstrates how to use the bytes.HasSuffix function to check if a byte slice ends with a specified suffix.

Example

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Define the main byte slice
	data := []byte("document.pdf")

	// Define the suffix to check
	suffix := []byte(".pdf")

	// Use bytes.HasSuffix to check if the slice ends with the suffix
	hasSuffix := bytes.HasSuffix(data, suffix)

	// Print the result
	fmt.Printf("Does the byte slice end with '%s'? %v\n", suffix, hasSuffix)
}

Output:

Does the byte slice end with '.pdf'? true

Suffix Not Found

This example shows how bytes.HasSuffix behaves when the suffix is not found at the end of the byte slice.

Example

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Define the main byte slice
	data := []byte("document.pdf")

	// Define a suffix that is not at the end
	suffix := []byte(".txt")

	// Use bytes.HasSuffix to check
	hasSuffix := bytes.HasSuffix(data, suffix)

	// Print the result
	fmt.Printf("Does the byte slice end with '%s'? %v\n", suffix, hasSuffix)
}

Output:

Does the byte slice end with '.txt'? false

Checking for Multiple Suffixes

This example demonstrates how to check for multiple potential suffixes using bytes.HasSuffix.

Example

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Define the main byte slice
	data := []byte("image.jpeg")

	// Define potential suffixes to check
	suffixes := [][]byte{
		[]byte(".jpg"),
		[]byte(".jpeg"),
		[]byte(".png"),
	}

	// Check if the slice ends with any of the suffixes
	for _, suffix := range suffixes {
		if bytes.HasSuffix(data, suffix) {
			fmt.Printf("The byte slice ends with '%s'.\n", suffix)
			return
		}
	}

	fmt.Println("No known suffix found.")
}

Output:

The byte slice ends with '.jpeg'.

Explanation:

  • bytes.HasSuffix checks if the byte slice s ends with the specified suffix suffix.
  • The function is useful for validation tasks where the end of the data determines how it should be processed.

Real-World Use Case

Verifying File Extensions

In real-world applications, bytes.HasSuffix can be used to verify file extensions, ensuring that the file ends with the expected extension before performing operations like opening or processing the file.

Example: Checking for Supported File Types

package main

import (
	"bytes"
	"fmt"
)

func main() {
	// Simulate a file name
	fileName := []byte("photo.png")

	// Define supported file extensions
	supportedExtensions := [][]byte{
		[]byte(".jpg"),
		[]byte(".jpeg"),
		[]byte(".png"),
	}

	// Check if the file has a supported extension
	for _, ext := range supportedExtensions {
		if bytes.HasSuffix(fileName, ext) {
			fmt.Printf("The file '%s' has a supported extension '%s'.\n", fileName, ext)
			return
		}
	}

	fmt.Println("The file does not have a supported extension.")
}

Output:

The file 'photo.png' has a supported extension '.png'.

Explanation:

  • The example demonstrates how bytes.HasSuffix can be used to check if a file has a supported extension before processing it, ensuring compatibility with the file type.

Conclusion

The bytes.HasSuffix function in Go is a quick and efficient way to check whether a byte slice ends with a specified suffix. Whether you're verifying file extensions, parsing URL paths, or processing input data with known suffixes, bytes.HasSuffix provides a simple and reliable solution for these tasks. Its ability to handle different suffixes and return a straightforward boolean result makes it used in data processing.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare